package net.hzfanqun.nutz.demo;

import java.sql.SQLException;
import java.util.List;

import org.apache.log4j.Logger;
import org.nutz.dao.Dao;
import org.nutz.ioc.Ioc;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.json.Json;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.Param;

import com.alibaba.druid.pool.DruidDataSource;

import net.hzfanqun.nutz.bean.Man;

@IocBean
@Ok("json")
public class HelloWorldDao {
	private static Logger logger = Logger.getLogger(HelloWorldDao.class);

	@Inject
	private Dao dao;

	@At("/display")
	public String diplay(Ioc ioc) throws SQLException {
		// System.out.println("ioc equals Mvcs.getIoc() ? " + (ioc == Mvcs.getIoc()));
		// System.out.println("Mvcs.getIoc=" + Mvcs.getIoc());
		DruidDataSource ds = ioc.get(DruidDataSource.class, "dataSourceDruid");
		// System.out.println("DataSource: " + ds);
		// Dao dao = new NutDao(ds);
		// 第一次运行生成表
		dao.create(Man.class, false);
		// Man p = new Man();
		List<Man> list = dao.query(Man.class, null, null);
		String str = Json.toJson(list);
		// System.out.println("display : " + str);
		return str;
	}

	@At("/insert")
	public String insert(@Param("name") String name, @Param("age") String age, Ioc ioc) throws SQLException {
		// DruidDataSource ds = ioc.get(DruidDataSource.class, "dataSourceDruid");

		// Dao dao = new NutDao(ds);
		Man p = new Man();
		p.setName(name);
		p.setAge(age);

		dao.insert(p);
		// logger.debug(dao.update(p));
		String str = "sucess:'ok'";
		return str;
	}

	@At("/update")
	public String update(@Param("name") String name, @Param("age") String age, Ioc ioc) throws SQLException {
		// DruidDataSource ds = ioc.get(DruidDataSource.class, "dataSourceDruid");

		// Dao dao = new NutDao(ds);
		Man p = new Man();
		p.setName(name);
		p.setAge(age);

		// dao.update(p);
		logger.debug(dao.update(p));
		String str = "sucess:'ok'";
		return str;
	}

	@At("/delete")
	public String delete(@Param("name") String name, @Param("age") String age, Ioc ioc) throws SQLException {
		// DruidDataSource ds = ioc.get(DruidDataSource.class, "dataSourceDruid");

		// Dao dao = new NutDao(ds);
		Man p = new Man();
		p.setName(name);
		p.setAge(age);

		dao.delete(p);
		// logger.debug(dao.update(p));
		String str = "sucess:'ok'";
		return str;
	}
}
